package com.qingcloud.base.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 基础异常类
 *
 * @author wangjinnan
 */
public class WamingException extends RuntimeException {

    private final Integer code;

    private final String message;

    public WamingException(String message) {
        this(505, message);
    }

    public WamingException(Integer code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public WamingException(WamingExceptionEnum wamingExceptionEnum) {
        this(wamingExceptionEnum.code, wamingExceptionEnum.message);
    }
    private WamingException(Integer errorCode, String errorMessage, Throwable cause) {
        super(errorCode + " - " + getMessage(errorMessage) + " - " + getMessage(cause), cause);
        message = errorMessage;
        code=errorCode;
    }
    public static WamingException asWMException(Integer errorCode, String message) {
        return new WamingException(errorCode, message);
    }

    public static WamingException asWMException(Integer errorCode, String message, Throwable cause) {
        if (cause instanceof WamingException) {
            return (WamingException) cause;
        }
        return new WamingException(errorCode, message, cause);
    }

    public static WamingException asWMException(Integer errorCode, Throwable cause) {
        if (cause instanceof WamingException) {
            return (WamingException) cause;
        }
        return new WamingException(errorCode, getMessage(cause), cause);
    }


    public Integer getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    private static String getMessage(Object obj) {
        if (obj == null) {
            return "";
        }

        if (obj instanceof Throwable) {
            StringWriter str = new StringWriter();
            PrintWriter pw = new PrintWriter(str);
            ((Throwable) obj).printStackTrace(pw);
            return str.toString();
        } else {
            return obj.toString();
        }
    }



}
